package cn.tedu.eguser1.base.exception;

import cn.tedu.eguser1.base.response.JsonResult;
import cn.tedu.eguser1.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常处理器
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //2封装参数的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data=ex.getFieldError().getDefaultMessage();
        log.error("ConstrainViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERRROR,data);
    }
    //3非封装参数出先的异常
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstrainViolationException(ConstraintViolationException ex){
        //delete id 车辆id必须在1-100之间
        String data=ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException"+data);
        return new JsonResult(StatusCode.VALIDATED_ERRROR,data);
    }


}
